package net.itemzone.framework.webservice.cxf.client;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import net.itemzone.framework.webservice.cxf.SoapAuthenticationConstants;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/** 
 * <p>Title: </p> 
 * <p>Description: </p>
 * <p>Company: 深圳任子行网络技术有限公司</p> 
 * @version 1.00 May 31, 2009
 * @author ZhaoJunFei
 *  
 * Modified History: 
 *  
 */
public class SoapClientAuthenticationInterceptor extends AbstractPhaseInterceptor<Message>{
	private SoapClientAuthentiactionHandler soapClientAuthentiactionHandler;
	public SoapClientAuthenticationInterceptor(){
		super(Phase.WRITE);
	}
	public SoapClientAuthenticationInterceptor(String phase) {
		super(phase);
	}
	public void handleMessage(Message msg) throws Fault {
		SoapMessage message = (SoapMessage)msg;
		Map namespaceMap = new HashMap();
		namespaceMap.put(SoapAuthenticationConstants.ELEMENT_INDEX, soapClientAuthentiactionHandler.getDefaultNamespace());
		message.put("soap.env.ns.map", namespaceMap);
		List<Header> headers= message.getHeaders();   
        headers.add(getHeader(SoapAuthenticationConstants.USERNAME, soapClientAuthentiactionHandler.getDefaultUserName()));   
        headers.add(getHeader(SoapAuthenticationConstants.PASSWORD, soapClientAuthentiactionHandler.getDefaultPassword()));   
	}
	private Header getHeader(String key, String value)   
    {   
            QName qName=new QName(soapClientAuthentiactionHandler.getDefaultNamespace(), key, SoapAuthenticationConstants.ELEMENT_INDEX);   
            Document document=DOMUtils.createDocument();   
            Element element=document.createElement(SoapAuthenticationConstants.ELEMENT_INDEX + ":" + key);   
            element.setTextContent(value);   
            SoapHeader header=new SoapHeader(qName, element);   
            return(header);   
    }   
	
	public void setSoapClientAuthentiactionHandler(
			SoapClientAuthentiactionHandler soapClientAuthentiactionHandler) {
		this.soapClientAuthentiactionHandler = soapClientAuthentiactionHandler;
	}
}
